// Why is the code so rubbed? It's missing your perfection.
import React from 'react';
import { connect } from 'react-redux';
import {Alert, Button, Col, Dropdown, Form, Icon, Menu, message, Popconfirm, Popover, Row, Spin, Tag} from 'antd';
import { addCalculate, currencyPrecisionCal, messages, queryCurrencyPrecision, deepFullCopy } from 'share/common';
import corporatePaymentReportService from 'containers/corporate-payment-report/corporate-payment-report.service';
import errorMessage from 'share/errorMessage';
import SlideFrame from 'components/slide-frame';
import Condition from 'components/condition';
import moment from 'moment';
import ResizeTable from 'components/resize-table';
import Space from "components/space";
import antdCommon from 'share/prototype-extend/antd-common';
const { renderPopover } = antdCommon;
import defaultExpenseTypeIcon from 'images/expense/default-expense-type.png'
import {ExpandIcon, wrappedExpandAllRow} from "components/table/table-expand-all";
import Invoice from "containers/my-account/invoice";
import PayWithInvoice from "./pay-with-invoice";
import PayWithPreviousInvoice from "./pay-with-previous-invoice";
import PayWithNoInvoice from "./pay-with-no-invoice";
import ListSelector from "components/list-selector";
import NewExpense from "../../../my-account/new-expense";
import Chooser from "components/chooser";

const { If } = Condition;

class PayInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      payInfoList: [],//付款行信息
      payInfo: {},//付款行信息
      columns: [{
        title: messages('finance-9.key42')/*类型*/,
        dataIndex: 'paymentScheduleType',
        render: value => this.paymentScheduleType[value] || '-',
        width: 100
      }, {
        title: messages('finance-9.key43')/*费用/付款类型*/,
        dataIndex: 'prepaymentTypeName',
        render: (value, record) => this.renderTypeCard(value, record),
        width: 280
      }, {
        title: messages('finance-9.key17')/*本次支付金额*/,
        dataIndex: 'planedAmount',
        render: (value, record) => this.renderMoney(record),
        width: 200
      }, {
        title: messages('finance-9.key44')/*收款账户*/,
        dataIndex: 'payeeName',
        render: (value, record) => this.columnPayObject(record),
        width: 200
      },{
        title: messages('finance-9.key45')/*付款属性*/,
        dataIndex: 'remark',
        render: (value, record) => this.columnPayAttributes(record),
        width: 220
      }],
      loading: true,//加载ing
      refreshExpense: false,
      expandedRowKeys: [],
      expandedAll: false,
      extraAmountInfo: {},
      show: false,
      payInfoDetail: null,
      prePaymentList: [],
      editMode: false,
      availableType: [] //启用功能类型
    };
  }

  paymentScheduleType = {
    1001: messages('finance-9.key46')/*到票支付*/,
    1002: messages('finance-9.key47')/*前期发票付款*/,
    1003: messages('finance-9.key48')/*预付付款*/
  };

  slideContent = {
    1001: PayWithInvoice,
    1002: PayWithPreviousInvoice,
    1003: PayWithNoInvoice
  };

  componentWillMount() {
    const { isWaitForAudit, expenseInfo, formInfo, entry } = this.props;
    const { columns } = this.state;
    if((entry === 'my' && expenseInfo.status === 1001) && !columns.filter(i => i.dataIndex === 'id').length) {
      this.setState({
        columns: columns.concat([{
          title: messages('common.operation'),
          dataIndex: 'id',
          width: 120,
          render: (value, record) => this.renderOperateColumn(record)
        }])
      })
    }
    let customFormPropertyMap = formInfo['customFormPropertyMap'];
    let availableType = JSON.parse(customFormPropertyMap['corp.payment.available.type'] || null) || [];
    this.setState({ availableType });
    if(availableType.indexOf(1003) > -1 && expenseInfo.status === 1001) {
      this.getPrePaymentList();
    }
  }

  componentDidMount() {
    if(this.props.firstMount) {
      this.getList();
    }
  }

  getPrePaymentList = () => {
    const { expenseInfo: { setOfBooksId }, formInfo: { formOID } } = this.props;
    let params = { formOID };
    corporatePaymentReportService.getPrePaymentList(setOfBooksId, params).then(res => {
      this.setState({ prePaymentList: res.data });
    })
  };

  //查询付款行信息
  getList = async () => {
    let extraAmountInfo, payInfoList;
    let payingInfoList = () => {
      corporatePaymentReportService.queryPayingInfoList(this.props.expenseInfo.id)
        .then(res => {
          const { corpPaymentScheduleListList, ...rest } = res.data;
          payInfoList = corpPaymentScheduleListList;
          extraAmountInfo = rest;
        }).catch(e => {
          payInfoList = [];
          extraAmountInfo = {};
          errorMessage(e.response);
        }).finally(() => {
          this.setState({ loading: false, payInfoList, extraAmountInfo },
            () => this.props.refreshPayInfoList(payInfoList)
          );
        });
    };
    this.setState({ loading: true, payInfoList: [] }, payingInfoList);
  };

  renderTypeCard = (prepaymentTypeName, record) => {
    if(prepaymentTypeName || !record.invoiceViewDTO) {
      return renderPopover(prepaymentTypeName)
    }
    return renderPopover(
      <div className='expense-card'>
        <img src={record.invoiceViewDTO.expenseTypeIconURL || defaultExpenseTypeIcon} className='expense-card-icon' />
        <div className='expense-card-name'>{record.invoiceViewDTO.expenseTypeName}</div>
        <div className='expense-card-info'>
          {messages('finance-9.key49')/*到票费用金额*/}：
          {record.invoiceViewDTO.currencyCode + ' ' + record.invoiceViewDTO.amount.toFixed(queryCurrencyPrecision(record.currencyCode))}
        </div>
        {record.invoiceViewDTO.comment && <div className='expense-card-info'>
          {messages('common.remark')/*备注*/}：
          {record.invoiceViewDTO.comment || '-'}
        </div>}
      </div>,
      triggerNode => triggerNode.parentNode
    )
  };

  renderMoney = (record) => {
    return renderPopover(
      <div className='money-box'>
        <div className='money-box-total-amount'>
          {record.currencyCode + ' ' +
          (record[record.paymentScheduleType === 1003 ? 'amount' : 'planedAmount'] || 0)
            .toFixed(queryCurrencyPrecision(record.currencyCode))}
        </div>
        <If value={record.paymentScheduleType === 1001 && record.writeOffAmount !== undefined}>
          <div className='money-box-write-off-amount'>
            {messages('finance-9.key9')/*核销金额*/}：
            {(record.writeOffAmount || 0).toFixed(queryCurrencyPrecision(record.currencyCode))}
          </div>
        </If>
        <If value={record.paymentScheduleType === 1001 && record.deferredPaymentAmount !== undefined}>
          <div className='money-box-info'>
            {messages('finance-9.key50')/*延迟支付金额*/}：
            {(record.deferredPaymentAmount || 0).toFixed(queryCurrencyPrecision(record.currencyCode))}
          </div>
        </If>
      </div>,
      triggerNode => triggerNode.parentNode
    )
  };

  renderOperateColumn = record => {
    return (
      <Popconfirm
        title={messages('finance-9.key51')/*确定删除该付款行吗?*/}
        onConfirm={e => this.handleDeletePayInfo(record, e)}
        okText={messages('common.ok')/*确定*/}
        cancelText={messages('common.cancel')/*取消*/}
      >
        <a onClick={e => e.stopPropagation()}>{messages('common.delete')}</a>
      </Popconfirm>
    )
  };

  //付款对象
  columnPayObject = (record) => {
    const jsx_map = [
      <div>{messages('finance-9.key52')/*账号*/}：{record[record.paymentScheduleType === 1003 ? 'payeeAccountNumber' : 'accountNumber']}</div>,
      <div>{messages('finance-9.key53')/*户名*/}：{record[record.paymentScheduleType === 1003 ? 'payeeAccountName' : 'accountName']}</div>
    ];
    return (
      <Popover content={jsx_map}>{jsx_map}</Popover>
    );
  };

  columnPayAttributes = (record) => {
    let element = [
      <div>
        {messages('finance-9.key18')/*付款方式*/}：
        {record.paymentMethodName || (record.cashPaymentMethod ? (record.cashPaymentMethod.description || '-') : '-')}
      </div>,
      <div>{messages('finance-9.key19')/*计划付款日期*/}: { record.planedPaymentDate ? moment(record.planedPaymentDate).format('YYYY-MM-DD') : '-'}</div>
    ];
    return (
      <Popover content={element}>{element}</Popover>
    );
  };

  //列扩展信息
  renderInvoiceExpanded = record => {
    let result = [];
    if(record.invoiceViewDTO && record.invoiceViewDTO.summaryInfo) {
      result.push(
        <div className='corporate-payment-report-detail-pay-summary' key='summaryInfo'>
          {record.invoiceViewDTO.summaryInfo.replace(/&#13;/g, ' ')}
        </div>
      )
    }
    const infoList = [];
    record.invoiceViewDTO && record.invoiceViewDTO.invoiceLabels.map(label => {
      if(label.level === 'INFO') {
        infoList.push(label.name);
      } else {
        let className = label.level === 'WARN' ? 'warning-expanded-row' : (label.level === 'ERROR' ? 'error-expand-row' : '');
        let content = <div>
          {label.name}
          {label.toast && label.toast.split('&#13;').map((item, index) => {
            if (index === 0)
              return <span>：{item}</span>;
            return <div>{item}</div>
          })}
        </div>;
        if(label.name) {
          result.push(
            <div className={`expanded-row-list ${className}`} key={`type-${result.length}`}>
              {renderPopover(content)}
            </div>
          )
        }
      }
    });
    if(infoList.length > 0) {
      let content = infoList.join('/');
      result.push(
        <div className="expanded-row-list" key={`type-${result.length}`}>
          {renderPopover(content)}
        </div>
      )
    }
    record.invoiceViewDTO && record.invoiceViewDTO.receiptList.map((invoice, index) => {
      result.push(
        <div className='corporate-payment-report-detail-pay-invoice' key={`invoice-${index}`}>
          <Invoice invoiceList={[invoice]} disabledEdit/>
        </div>
      )
    });
    return result.length === 0 ? null : <div className='corporate-payment-report-detail-pay-row'>{result}</div>;
  };

  renderPopAmount = (params) => {
    return `${params.currency} ${this.filterMoney(params.amount, queryCurrencyPrecision(params.currency))}`;
  };

  //获取付款币种金额
  getPayingCurrencyCodeAmount = (attr) => {
    let { expenseInfo } = this.props;
    return <span key={attr}>{expenseInfo.currencyCode}&nbsp;{this.getPayingAmount(attr)}</span>
  };

  //获取总金额
  getAmount = (attr) => {
    const { expenseInfo } = this.props;
    const { extraAmountInfo } = this.state;
    return expenseInfo.currencyCode + ' ' + this.filterMoney(extraAmountInfo[attr] || 0, queryCurrencyPrecision(expenseInfo.currencyCode), true);
  };

  handleClick = (paymentScheduleType, operateMode, prepaymentTypeId) => {
    switch (paymentScheduleType) {
      case 1001:
        this.handleNewPayInfo(paymentScheduleType, operateMode);
        break;
      case 1002:
        this.setState({ show: true });
        break;
      case 1003:
        this.setState({ payInfoDetail: { prepaymentTypeId } },
          () => this.handleNewPayInfo(paymentScheduleType, operateMode));
    }
  };

  onSelectedPayInfo = payInfoDetail => {
    if(!payInfoDetail) {
      message.error(messages('finance-9.key96')/*请选择需要支付的单据！*/);
      return;
    }
    this.setState({
      payInfoDetail, show: false
    }, () => this.handleNewPayInfo(1002, 'CREATE'));
  };

  handleNewPayInfo = (paymentScheduleType, operateMode, record) => {
    const { expenseInfo, isWaitForAudit, entry, formInfo, jobInfo, isAuditEditable } = this.props;
    const { payInfoDetail, editMode } = this.state;
    let hasSupplierSetting = formInfo['customFormPropertyMap'] ? (formInfo['customFormPropertyMap']['document.venmasteradd.enable']) : '';
    SlideFrame.open({
      title: this.renderTitle(operateMode, paymentScheduleType),
      content: this.slideContent[paymentScheduleType],
      width: 800,
      className: 'corporate-payment-report-pay-info-slide',
      afterClose: (needRefresh) => {
        needRefresh && this.getList();
        needRefresh && this.props.refreshInfo();
        this.setState({ payInfoDetail: null });
      },
      params: {
        editMode,
        jobInfo,
        expenseInfo,
        hasSupplierSetting,
        operateMode,
        isWaitForAudit,
        entry,
        payInfoDetail,
        isAuditEditable,
        paymentScheduleId: record ? record.id : null,
        customFormPropertyMap: formInfo['customFormPropertyMap'] || {}
      },
    }, this);
  };

  handleDeletePayInfo = (record, e) => {
    e.stopPropagation();
    this.setState({ loading: true });
    corporatePaymentReportService.deletePayInfoDetail(record)
      .then(() => message.success(messages('common.operate.success')/*操作成功*/))
      .then(() => this.getList())
      .catch(e => errorMessage(e.response))
      .finally(() => this.setState({ loading: false }));
  };

  renderTitle = (operateMode, paymentScheduleType) => {
    return (
      <div>
        {operateMode === "CREATE" ?
          messages('common.next')/*新建*/ + this.paymentScheduleType[paymentScheduleType] :
          messages('finance-9.key54')/*查看信息*/
        }
      </div>
    )
  };

  render() {
    const { expenseInfo } = this.props;
    const { columns, payInfoList, loading, expandedAll, expandedRowKeys, show, prePaymentList,
      availableType
    } = this.state;

    let { showIcon, onExpand, onExpandAllRows } = wrappedExpandAllRow(
      {
        dataSource: payInfoList,
        expandedAll,
        expandedRowKeys,
        rowKey: 'id',
        expandedRowRender: this.renderInvoiceExpanded,
      }, params => this.setState(params));
    let tableTitle = (
      <div className={'column-title'}>
        <div>
          {messages('finance-9.key55')/*本次支付总金额*/}：<span className='column-title-amount'>{this.getAmount('paymentTotalAmount')}</span> =
          {messages('finance-9.key56')/*到票支付金额*/}：<span className='column-title-amount'>{this.getAmount('newInvoicePaymentTotalAmount')}</span> +
          {messages('finance-9.key57')/*预付付款金额*/}：<span className='column-title-amount'>{this.getAmount('preparePaymentTotalAmount')}</span> +
          {messages('finance-9.key58')/*前期发票付款金额*/}：<span className='column-title-amount'>{this.getAmount('preInvoicePaymentTotalAmount')}</span>
        </div>
        <div>
          {messages('finance-9.key59')/*到票费用总金额*/}：<span className='column-title-amount'>{this.getAmount('newInvoiceTotalAmount')}</span> =
          {messages('finance-9.key56')/*到票支付金额*/}：<span className='column-title-amount'>{this.getAmount('newInvoicePaymentTotalAmount')}</span> +
          {messages('finance-9.key9')/*核销金额*/}：<span className='column-title-amount'>{this.getAmount('writeOffTotalAmount')}</span> +
          {messages('finance-9.key60')/*延期支付金额*/}：<span className='column-title-amount'>{this.getAmount('deferredPaymentTotalAmount')}</span>
        </div>
      </div>
    );
    const menu = (
      <Menu onClick={item => this.handleClick(1003, 'CREATE', item.key)}>
        {prePaymentList.map(i => <Menu.Item key={i.id}>{i.prepaymentTypeName}</Menu.Item>)}
      </Menu>
    );
    return (
      <div className="pay-info-list">
        {/*头部信息*/}
        <div className="header-title">{messages('finance-9.key26')/*付款信息*/}</div>
        <If value={expenseInfo.status === 1001}>
          <Space style={{marginBottom: 12}}>
            {availableType.sort((a, b) => a -b).map(i => i === 1003 ? (
              <Dropdown overlay={menu} placement="bottomCenter">
                <Button type="primary">
                  {messages('finance-9.key48')/*预付付款*/}
                  &nbsp;&nbsp;
                  <Icon type="down"/>
                </Button>
              </Dropdown>
            ) : (
              <Button
                type='primary'
                icon="plus"
                onClick={() => this.handleClick(i, 'CREATE')}
              >
                {this.paymentScheduleType[i]}
              </Button>
              )
            )}
          </Space>
        </If>
        {/*<ExpandIcon onExpandAllRows={onExpandAllRows} expandedAll={expandedAll} showIcon={showIcon}/>*/}
        <ResizeTable
          showUtils
          tableName="corporate-payment-report-pay-info"
          columns={columns}
          rowKey="id"
          dataSource={payInfoList}
          loading={loading}
          title={() => tableTitle}
          expandedRowRender={this.renderInvoiceExpanded}
          expandedRowKeys={expandedRowKeys}
          onExpand={onExpand}
          onRow={
            record => ({
              onClick: () => this.handleNewPayInfo(record.paymentScheduleType, 'EDIT', record)
            })
          }
          bordered
          pagination={false}
        />
        <ListSelector
          type='available_payment_info'
          onOk={(value) => this.onSelectedPayInfo(value.result[0])}
          visible={show}
          single={true}
          extraParams={{expId: expenseInfo.id}}
          onCancel={() => this.setState({ show: false })}
          hidePagination={true}
        />
      </div>
    )
  }
}

PayInfo.propsType = {
  selectInvoiceOIDs: React.PropTypes.array,//选择费用的OID
  operateMode: React.PropTypes.string,//操作模式 readOnly:只读。edit:编辑
  clearSelectInvoiceOIDs: React.PropTypes.func,//清除选择费用
  pageFrom: React.PropTypes.string,//场景来源。myView：自己查看场景；approveView：审批人查看场景 auditView：审核者查看场景
  formInfo: React.PropTypes.object, //表单详情
  expenseRowIsEdit: React.PropTypes.bool, //费用行是否被修改了，若true，则需要重新渲染付款行
  afterReload: React.PropTypes.func, //付款行重新渲染后的回调
  userOid: React.PropTypes.string,
  expenseReportInvoices: React.PropTypes.array, //费用行
  handleLineId: React.PropTypes.func, //把列表行回传给父级
  expenseInfo: React.PropTypes.object, //单据详情
};

PayInfo.defaultProps = {
  handleLineId: () => {},
  expenseReportInvoices: []
};

PayInfo.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    options: state.login.options,
  }
}

const WrappedPayInfo = Form.create()(PayInfo);

export default connect(mapStateToProps)(WrappedPayInfo)
